package com.meixiaoliang.portal.modular.system.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.meixiaoliang.portal.core.rongyun.RongyunService;
import com.meixiaoliang.portal.core.util.AssertUtil;
import com.meixiaoliang.portal.core.util.EncryptUtil;
import com.meixiaoliang.portal.core.util.ExcelUtil;
import com.meixiaoliang.portal.core.util.ResponseUtil;
import com.meixiaoliang.portal.modular.system.model.User;
import com.meixiaoliang.portal.modular.system.model.enums.ExcelTypeEnum;
import com.meixiaoliang.portal.modular.system.model.result.LoginResult;

@RestController
public class LoginController extends BaseController {

    @Autowired
    private RongyunService rongyunService;

    /** 密码加密的盐 */
    @Value("${password.salt}")
    public String          salt;
    /** 密码转换次数 */
    @Value("${password.transTime}")
    public int             transTime;
    /** 融云appKey */
    @Value("${rongyun.appKey}")
    public String          rongyunAppKey;

    /**
     * 用户未登录
     */
    @GetMapping("notLogin")
    @CrossOrigin
    public String notLogin() {
        return ResponseUtil.buildNotLoginResponse();
    }

    /**
     * 登录用户名密码登录
     */
    @RequestMapping(value = "login", method = { RequestMethod.POST, RequestMethod.GET })
    public String login(String name, String password, boolean rememberMe) {

        AssertUtil.notBlank(name, "用户名不能为空");
        AssertUtil.notBlank(password, "密码不能为空");

        LoginResult result = new LoginResult();

        // shiro 前置工作
        UsernamePasswordToken authenticationToken = new UsernamePasswordToken(name, EncryptUtil.transform(password, salt, transTime));
        authenticationToken.setRememberMe(rememberMe);
        Subject subject = SecurityUtils.getSubject();

        try {

            // 登录
            subject.login(authenticationToken);
            result.setLoginResult(true).setMessage("登录成功");

            User user = getUser();
            result.setUser(new User().setRealName(user.getRealName()));
            //            result.setUser(new User().setRealName(user.getRealName()).setRongyunAppKey(rongyunAppKey)
            //                .setRongyunToken(rongyunService.getToken(user.getRongyunId(), user.getRealName())));

            logger.info("登录成功: userId={}, userName={}", user.getId(), user.getRealName());

        } catch (AuthenticationException e) {

            if (e instanceof UnknownAccountException) {
                logger.info("用户不存在: userName={}", name);
                result.setMessage("用户不存在");
            }
            //
            else if (e instanceof DisabledAccountException) {
                logger.info("用户禁止登录: userName={}", name);
                result.setMessage("用户禁止登录");
            }
            //
            else if (e instanceof IncorrectCredentialsException) {
                logger.info("密码错误: userName={}, password={}", name, password);
                result.setMessage("密码错误");
            }
            //
            else {
                logger.info("用户登录失败,未知异常: userName={}", name);
                result.setMessage("用户登录失败");
            }

        }

        return ResponseUtil.buildSuccessResponse(result);
    }

    /**
     * 登出操作自己写, 这样可以实现统一的请求
     */
    @RequestMapping("/logout")
    public String logout() {
        logger.info("登出请求, userId={}, userName={}", getCurrentUserId(), getUser().getRealName());
        getSubject().logout();
        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 刷新缓存
     */
    @PostMapping("/refreshCache")
    public String refreshCache() {
        userService.refreshCache();
        logger.info("缓存刷新完毕");
        return ResponseUtil.buildSuccessResponse();
    }

    /**
     * 列表数据导出到 excel
     */
    @PostMapping("/xxxxxxx")
    public String xxxx() {
        ExcelUtil.exportList(String.valueOf(System.currentTimeMillis()), null, ExcelTypeEnum.DICT, dictionaryService.list(null));
        return ResponseUtil.buildSuccessResponse();
    }

}
